package com.hoshiicloud.user.service.impl.store;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.constant.DeleteStatusEnum;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.user.entity.company.Member;
import com.hoshiicloud.user.entity.store.StoreDepartment;
import com.hoshiicloud.user.entity.store.StoreUsers;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.store.StoreUsersMapper;
import com.hoshiicloud.user.param.store.StoreUsersQueryParam;
import com.hoshiicloud.user.service.rbac.IMemberService;
import com.hoshiicloud.user.service.store.StoreDepartmentService;
import com.hoshiicloud.user.service.store.StoreUsersService;
import com.hoshiicloud.user.vo.store.StoreUsersVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 店铺用户 服务实现类
 * </p>
 *
 * @author campchen
 * @since 2019-07-24
 */
@Slf4j
@Service
public class StoreUsersServiceImpl extends ServiceImpl<StoreUsersMapper, StoreUsers> implements StoreUsersService {

    @Autowired
    private StoreDepartmentService storeDepartmentService;

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private StoreUsersMapper storeUsersMapper;

    /**
     * @return IPage
     * @description: 分页查询店铺用户
     */
    @Override
    @Logable(authName = "店铺管理-店铺用户管理-分页查询店铺用户")
    //@Cacheable(cacheNames = "StoreUsers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public IPage<StoreUsers> getPage(IPage page, QueryWrapper queryWrapper) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * @param id
     * @return com.hoshiicloud.store.entity.StoreUsers
     * @description: 根据id查询店铺用户
     */
    @Override
    @Cacheable(cacheNames = "StoreUsers", key = "#root.targetClass.simpleName + ':' + #root.methodName + ':' + #id")
    @Logable(authName = "店铺管理-店铺用户 -查询店铺用户 ")
    public StoreUsers getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * @return boolean
     * @description: 新增店铺用户
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreUsers", allEntries = true)
    @Logable(authName = "店铺管理-店铺用户-新增店铺用户")
    @Override
    public boolean save(StoreUsers entity) {
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        if(entity.getUserCode()==null || entity.getUserCode().equals("")){
            entity.setUserCode(String.valueOf((int) ((Math.random() * 9 + 1) * 1000000000)));
        }
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @return boolean
     * @description: 修改店铺用户
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreUsers", allEntries = true)
    @Logable(authName = "店铺管理-店铺用户管理-修改店铺用户")
    @Override
    public boolean updateById(StoreUsers entity) {
        entity.setModifiedTime(LocalDateTime.now());
//        StoreDepartment response = storeDepartmentService.getById(entity.getDepartmentid());
//        if (null == response||"".equals(response)) {
//            throw new ServiceException(CommonError.error("修改失败，没有找到部门信息"));
//        }
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreUsers", allEntries = true)
    @Logable(authName = "店铺管理-店铺用户管理-删除店铺用户")
    @Override
    public boolean deleteStoreUsersById(Long id) {
        StoreUsers entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException(CommonError.error("删除店铺用户异常，无法找到店铺用户记录"));
        }
        entity.setModifiedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreUsers", allEntries = true)
    @Logable(authName = "店铺管理-店铺用户管理-禁用店铺用户")
    @Override
    public boolean forbidStoreUsersById(Long id) {
        StoreUsers entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException(CommonError.error("禁用店铺用户异常，无法找到店铺用户记录"));
        }
        entity.setModifiedTime(LocalDateTime.now());
        entity.setDeleted(2);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("禁用失败"));
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreUsers", allEntries = true)
    @Logable(authName = "店铺管理-店铺用户管理-解禁店铺用户")
    @Override
    public boolean notForbidStoreUsersById(Long id) {
        StoreUsers entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException(CommonError.error("解禁店铺用户异常，无法找到店铺用户记录"));
        }
        entity.setModifiedTime(LocalDateTime.now());
        entity.setDeleted(DeleteStatusEnum.UN_DELETED.getCode());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("解禁店铺用户失败"));
        }
        return true;
    }


    @Override
    @Cacheable(cacheNames = "StoreUsers", key = "#root.targetClass.simpleName + ':' + #root.methodName + ':' + #key")
    @Logable(authName = "店铺管理-店铺用户管理-根据id集合查询店铺用户")
    public List<StoreUsers> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 分页获取店铺员工列表
     * @param page
     * @param param
     * @return
     */
    @Override
    public IPage<StoreUsersVO> storeUserPageList(IPage<StoreUsersVO> page, StoreUsersQueryParam param) {
        return storeUsersMapper.storeUserPageList(page,param);
    }

    /**
     * 批量删除或禁用数据 flag=1 删除,flag=2 禁用
     * @param idsArr
     * @param flag
     * @return
     */
    @Override
    public boolean batchDeleteStoreUsers(List<Long> idsArr,int flag){
        return storeUsersMapper.batchDeleteStoreUsers(idsArr,flag);
    }

    /**
     * 店铺管理根据角色名称分页查询员工列表
     * @param page
     * @param param
     * @return
     */
    @Override
    public IPage<StoreUsersVO> getStoreUserByRoleName(IPage<StoreUsersVO> page, @Param("param") StoreUsersQueryParam param){
        return storeUsersMapper.getStoreUserByRoleName(page,param);
    }

    /**
     * 根据查询条件获取员工姓名列表
     * @param param
     * @return
     */
    @Override
    public List<Map> storeUserNameList(StoreUsersQueryParam param){
        return storeUsersMapper.storeUserNameList(param);
    }


}
